package com.photoeditor.demo.model.image.emoji;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.db.DataManager;
import com.photoeditor.demo.db.ExtraBean;
import com.photoeditor.demo.imageloader.GlideApp;
import com.photoeditor.demo.model.bean.EmojiBean;
import com.photoeditor.demo.model.bean.EmojiPageBean;
import com.photoeditor.demo.model.bean.PagePositionBean;
import com.photoeditor.demo.model.store.module.StoreOnlineBean;
import com.photoeditor.demo.model.store.module.StoreOnlineManager;
import com.photoeditor.demo.ui.widget.image.emoji.EmojiCheckableItem;
import com.photoeditor.demo.ui.widget.image.emoji.EmojiItem;
import com.photoeditor.demo.model.bean.stash.ARStickerResource;
import com.photoeditor.demo.model.bean.stash.DateStickerBean;
import com.photoeditor.demo.model.bean.stash.TimeStickerBean;
import com.photoeditor.demo.util.BitmapUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

public class LocalStickerData {
    /**
     * 加载Sticker的工具
     */
    private EmojiIconManager mIconManager;

    //所有Sticker的ApkBean
    private LinkedHashMap<String, StickerApkResource> mApkBean;

    //button的列表
    private ArrayList<StickerCategoryBean> mButtonPackages;

    private ArrayList<StoreOnlineBean> mStoreOnlineBeans;

    /**
     * 是否被回收了 如果被回收则需要重新init
     */
    private boolean isRecycled = false;

    /**
     * 单例对象
     */
    private static LocalStickerData mInstance;


    private LocalStickerData(Context context) {
        isRecycled = false;
        mIconManager = new EmojiIconManager();
        loadEmojiData(context);
    }

    public synchronized static LocalStickerData getInstance() {
        if (mInstance == null) {
            mInstance = new LocalStickerData(ComponentContext.getContext());
        } else {
            if (mInstance.isRecycled) {
                mInstance.isRecycled = false;
                mInstance.mIconManager = new EmojiIconManager();
                mInstance.loadEmojiData(ComponentContext.getContext());
            }
        }
        return mInstance;
    }

    public void setRecycled() {
        isRecycled = true;
    }

    public static int from = 1;

    /**
     * 初始化Emoji的信息
     *
     * @param context
     */
    public synchronized void loadEmojiData(Context context) {
        if (mApkBean == null) {
            mApkBean = new LinkedHashMap<String, StickerApkResource>();
        } else {
            mApkBean.clear();
        }

        if (mStoreOnlineBeans == null) {
            mStoreOnlineBeans = new ArrayList<>();
        } else {
            mStoreOnlineBeans.clear();
        }

        if (mButtonPackages == null) {
            mButtonPackages = new ArrayList<>();
        } else {
            mButtonPackages.clear();
        }

        mStoreOnlineBeans = StoreOnlineManager.getInstance().getAllStickerCategoryItemBeans();

        if (mStoreOnlineBeans == null || mStoreOnlineBeans.isEmpty()) {
            //没有获取到线上数据 就显示本地下载的

            //从数据库中获取到所有的包名
            ArrayList<ExtraBean> extraBeans = new ArrayList<>();
            //gif
            /*extraBeans.add(ExtraBean.create("gif",
                InsideStickerTool.STICKER_PKG_NAME_GIF,
                ExtraBean.TYPE_INTER,
                0,
                false,
                1,
                ExtraBean.RES_TYPE_INSTALLED, null, false));*/
            //内置emoji
            extraBeans.add(ExtraBean.create("emoji",
                    InsideStickerTool.STICKER_PKG_NAME_EMOJI,
                    ExtraBean.TYPE_INTER,
                    0,
                    false,
                    1,
                    ExtraBean.RES_TYPE_INSTALLED, null, false));

            //处理在外部安装但是数据库中不存在的包
            /*List<ResolveInfo> resolveInfos = StickerConstant.getAllInstalledStickerApk(context);
            for (ResolveInfo info : resolveInfos) {
                String pkgName = info.activityInfo.packageName;
                if (mApkBean.get(pkgName) == null) {//无记录
                    InstalledStickerResource stickerResource = new InstalledStickerResource(context, pkgName, true);
                    mApkBean.put(pkgName, stickerResource);
                    mButtonPackages.add(pkgName);
                    boolean isNeedBuy = stickerResource.isNeedBuy();
                    DataManager.getInstance().insertOrUpdateSticker(ExtraBean.create(stickerResource.getName(), stickerResource.getPkgName(),
                            ExtraBean.TYPE_OUTER_NOT_NEED_BUY, 0, true, stickerResource.isDownloadOnGP()));
                }
            }*/

//            extraBeans.addAll(DataManager.getInstance().getAllUsableSticker());

            //带量emoji
            /*extraBeans.add(ExtraBean.create(StickerConstant.APK_EMOJI_NAME
                , StickerConstant.APK_EMOJI_PKG_NAME_ALL
                , ExtraBean.TYPE_OUTER_NOT_NEED_BUY, false
                , 1
                , ExtraBean.RES_TYPE_INSTALLED
                , null));*/
            int count = extraBeans.size();
            for (int i = 0; i < count; i++) {
                ExtraBean bean = extraBeans.get(i);
                String pkgName = bean.getPkgName();
                if (bean.isType(ExtraBean.TYPE_INTER)) {
                    //内置的
                    mApkBean.put(pkgName, new InsideEmojiResource(context, pkgName, bean.getName()));
                    mButtonPackages.add(StickerCategoryBean.newResourceBean(pkgName, bean.getIsBuy()));
                } else {
                    if (bean.isResType(ExtraBean.RES_TYPE_UNINSTALLED)) {//未安装的
                        UninstalledStickerResource uninstalledStickerResource = new UninstalledStickerResource(context, pkgName, bean.getZipPath(), true, bean.isDownloadOnGP(), bean.getVersion());
                        if (uninstalledStickerResource.isExist()) {
                            mApkBean.put(pkgName, uninstalledStickerResource);
                            mButtonPackages.add(StickerCategoryBean.newResourceBean(pkgName, bean.getIsBuy()));
                        } else {//不存在删除数据库记录
//                            DataManager.getInstance().deleteSticker(pkgName, bean.getResType());
                        }
                    } else if (bean.isResType(ExtraBean.RES_TYPE_INSTALLED)) {//已经安装的
                        StickerApkResource stickerApkResource = null;
                        if (TextUtils.equals(pkgName, StickerConstant.APK_EMOJI_PKG_NAME_ALL)) {
                            stickerApkResource = new InstalledEmojiResource(context, pkgName, StickerConstant.EMOJI_GP_URL);
                            if (stickerApkResource.isExist()) {//存在
                                if (mApkBean.get(pkgName) == null) {
                                    mApkBean.put(pkgName, stickerApkResource);
                                    mButtonPackages.add(StickerCategoryBean.newResourceBean(pkgName, bean.getIsBuy()));
                                }
                            } else {
//                                DataManager.getInstance().deleteSticker(pkgName, bean.getResType());
                            }
                        } else {
                            stickerApkResource = new InstalledStickerResource(context, pkgName, true);
                            if (stickerApkResource.isExist()) {//存在
                                if (mApkBean.get(pkgName) == null) {
                                    mApkBean.put(pkgName, stickerApkResource);
                                    mButtonPackages.add(StickerCategoryBean.newResourceBean(pkgName, bean.getIsBuy()));
                                }
                            } else {
//                                DataManager.getInstance().deleteSticker(pkgName, bean.getResType());
                            }
                        }

                    }
                }
            }

        } else {
            //获取到线上数据 按线上顺序显示
            mApkBean.put(InsideStickerTool.STICKER_PKG_NAME_EMOJI, new InsideEmojiResource(context, InsideStickerTool.STICKER_PKG_NAME_EMOJI, "emoji"));
            mButtonPackages.add(StickerCategoryBean.newResourceBean(InsideStickerTool.STICKER_PKG_NAME_EMOJI, false));
            ExtraBean bean;
            for (StoreOnlineBean onlineBean : mStoreOnlineBeans) {
                String pkgName = onlineBean.getPkgName();
                if (DataManager.getInstance().isInstalled(pkgName)) {
                    bean = DataManager.getInstance().getStickerByPkgName(pkgName);
                    UninstalledStickerResource uninstalledStickerResource = new UninstalledStickerResource(context, pkgName, bean.getZipPath(), true, bean.isDownloadOnGP(), bean.getVersion());
                    if (uninstalledStickerResource.isExist()) {
                        mApkBean.put(pkgName, uninstalledStickerResource);
                        mButtonPackages.add(StickerCategoryBean.newResourceBean(pkgName, onlineBean.isBuy()));
                    } else {//不存在删除数据库记录
                        //DataManager.getInstance().deleteSticker(pkgName, bean.getResType());
                    }
                } else {
                    mApkBean.put(pkgName, new OnlineStickerResource(context, pkgName, onlineBean.getStickerUrls()));
                    mButtonPackages.add(StickerCategoryBean.newOnlineBean(pkgName, onlineBean.getTab(), onlineBean.isBuy()));
                }
            }
        }



    }

    /**
     * @param isNewVersion
     * @param indexMap     用于纪录某一个包在第几页
     * @return
     */
    public synchronized ArrayList<EmojiPageBean> getPageBeans(boolean isNewVersion, HashMap<String, PagePositionBean> indexMap) {
        ArrayList<EmojiPageBean> result = new ArrayList<EmojiPageBean>();
        indexMap.clear();
        int index = 0;

        /*PagePositionBean pageBean = new PagePositionBean();
        pageBean.setIndex(index);
        indexMap.put(InsideStickerTool.STICKER_PKG_NAME_GIF, pageBean);
        //gif 确保是在第一页
        EmojiPageBean bean = new EmojiPageBean(EmojiPageBean.TYPE_GIF, 0, InsideStickerTool.STICKER_PKG_NAME_GIF);
        result.add(bean);
        index++;
        pageBean.setPageNum(index - pageBean.getIndex());*/

//		int length = UNINSTALL_APK_PKG_NAME.length;
        for (StickerCategoryBean categoryBean : mButtonPackages) {
            String pkgName = categoryBean.getPkgName();
            if (InsideStickerTool.STICKER_PKG_NAME_GIF.equals(pkgName)) {
                //gif在上面添加过
                continue;
            }
            if (InsideStickerTool.STICKER_BTN_ICON_MAP.keySet().contains(pkgName)) {
                //EMOJI_APk和内置的属于一类
                PagePositionBean pageBean1 = new PagePositionBean();
                pageBean1.setIndex(index);
                indexMap.put(pkgName, pageBean1);

                InsideEmojiResource insideEmojiResource = (InsideEmojiResource) mApkBean.get(pkgName);

                /*//最近
                if(InsideStickerTool.STICKER_PKG_NAME_EMOJI.equals(pkgName)) {
                    result.add(new EmojiPageBean(EmojiPageBean.TYPE_RECENT, 0, insideEmojiResource.getPkgName(), insideEmojiResource.getEmojiColNum()
                            , insideEmojiResource.getEmojiPageNum(), insideEmojiResource.getVerticalSpacing(), insideEmojiResource.getHorizontalSpacing()
                            , insideEmojiResource.getEmojiWidth(), insideEmojiResource.getEmojiHeight(), insideEmojiResource.getItemWidth(), insideEmojiResource.getItemHeight()
                            , insideEmojiResource.getPageHeight(), insideEmojiResource.getBgColor()));
                    index++;
                }*/
                //AR贴纸
                if (/*from == InsideEmojiResource.FROM_STASH && */InsideStickerTool.STICKER_PKG_NAME_EMOJI.equals(pkgName)) {
                    ARStickerResource arStickerResource = insideEmojiResource.getARStickerResource();
                    result.add(new EmojiPageBean(EmojiPageBean.TYPE_AR_STICKER, 0, pkgName, arStickerResource.getEmojiColNum()
                            , arStickerResource.getEmojiPageNum(), arStickerResource.getVerticalSpacing(), arStickerResource.getHorizontalSpacing()
                            , arStickerResource.getEmojiWidth(), arStickerResource.getEmojiHeight(), arStickerResource.getItemWidth(), arStickerResource.getItemHeight()
                            , arStickerResource.getPageHeight(), arStickerResource.getBgColor(), categoryBean.isBuy()));
                    index++;
                }
                //内置
                int emojiNums = insideEmojiResource.getEmojiNames().length;
                int pageNums = emojiNums / insideEmojiResource.getEmojiPageNum();
                if (emojiNums % insideEmojiResource.getEmojiPageNum() != 0) {
                    pageNums++;
                }
                for (int i = 0; i < pageNums; i++) {
                    result.add(new EmojiPageBean(EmojiPageBean.TYPE_RESOURCES, i, pkgName, insideEmojiResource.getEmojiColNum()
                            , insideEmojiResource.getEmojiPageNum(), insideEmojiResource.getVerticalSpacing(), insideEmojiResource.getHorizontalSpacing()
                            , insideEmojiResource.getEmojiWidth(), insideEmojiResource.getEmojiHeight(), insideEmojiResource.getItemWidth(), insideEmojiResource.getItemHeight()
                            , insideEmojiResource.getPageHeight(), insideEmojiResource.getBgColor(), categoryBean.isBuy()));
                    index++;
                }

                //带量emoji
                /*InstalledEmojiResource resource = (InstalledEmojiResource) mApkBean.get(StickerConstant.APK_EMOJI_PKG_NAME_ALL);
                if (resource!= null && resource.isExist()) {//存在
                    indexMap.put(StickerConstant.APK_EMOJI_PKG_NAME_ALL, pageBean1);
                    int emojiNum = resource.getEmojiNames().length;
                    int pageNum = emojiNum / resource.getEmojiPageNum();
                    if (emojiNum % resource.getEmojiPageNum() != 0) {
                        pageNum++;
                    }
                    for (int k = 0; k < pageNum; k++) {
                        result.add(new EmojiPageBean(EmojiPageBean.TYPE_INSTALL_EMOJI_APK, k, resource.getPkgName(), resource.getEmojiColNum(), resource.getEmojiPageNum(),
                                resource.getVerticalSpacing(), resource.getHorizontalSpacing(),
                                resource.getEmojiWidth(), resource.getEmojiHeight(),
                                resource.getItemWidth(), resource.getItemHeight(),
                                resource.getPageHeight(), resource.getBgColor()));
                        index++;
                    }

                }*/

                /*ProductDriveStrategy.ProductDriveStrategyConfig config = getEmojiStrategy();
                if (config != null) {
                    if (config.isSwitch()) {
                        if (!ShareImageTools.getAppIsInstalled(ComponentContext.getContext(), config.getPackageName())) {
                            EmojiPageBean bean = new EmojiPageBean(EmojiPageBean.TYPE_GUIDE_DOWNLOAD, 0, StickerConstant.APK_EMOJI_PKG_NAME);
                            bean.setDownUrl(config.getGpLink());
                            result.add(bean);
                            index++;
                        }
                    }
                }*/

                pageBean1.setPageNum(index - pageBean1.getIndex());

            } else {//其他的如果没有安装都不会显示
                //下面是Stickers的相关处理
                StickerApkResource resource = mApkBean.get(pkgName);
                if (resource instanceof OnlineStickerResource) {
                    OnlineStickerResource onlineResource = (OnlineStickerResource) resource;
                    int resourceNum = onlineResource.getIconUrls().length;
                    int pageNum = resourceNum / onlineResource.getEmojiPageNum();
                    if (resourceNum % onlineResource.getEmojiPageNum() != 0) {
                        pageNum++;
                    }
                    PagePositionBean onlinePageBean = new PagePositionBean();
                    onlinePageBean.setIndex(index);
                    indexMap.put(onlineResource.getPkgName(), onlinePageBean);
                    for (int k = 0; k < pageNum; k++) {
                        result.add(new EmojiPageBean(EmojiPageBean.TYPE_ONLINE, k, onlineResource.getPkgName(), onlineResource.getEmojiColNum(), onlineResource.getEmojiPageNum(),
                                onlineResource.getVerticalSpacing(), onlineResource.getHorizontalSpacing(),
                                onlineResource.getEmojiWidth(), onlineResource.getEmojiHeight(),
                                onlineResource.getItemWidth(), onlineResource.getItemHeight(),
                                onlineResource.getPageHeight(), onlineResource.getBgColor(), categoryBean.isBuy()));
                        index++;
                    }
                    onlinePageBean.setPageNum(index - onlinePageBean.getIndex());
                } else if (resource instanceof InstalledStickerResource) {
                    InstalledStickerResource emojiApkBean = (InstalledStickerResource) resource;
                    if (emojiApkBean.isExist()) {//存在
                        int emojiNum = emojiApkBean.getEmojiNames().length;
                        int pageNum = emojiNum / emojiApkBean.getEmojiPageNum();
                        if (emojiNum % emojiApkBean.getEmojiPageNum() != 0) {
                            pageNum++;
                        }
                        PagePositionBean pageBean2 = new PagePositionBean();
                        pageBean2.setIndex(index);
                        indexMap.put(emojiApkBean.getPkgName(), pageBean2);
                        for (int k = 0; k < pageNum; k++) {
                            result.add(new EmojiPageBean(EmojiPageBean.TYPE_INSTALL_APK, k, emojiApkBean.getPkgName(), emojiApkBean.getEmojiColNum(), emojiApkBean.getEmojiPageNum(),
                                    emojiApkBean.getVerticalSpacing(), emojiApkBean.getHorizontalSpacing(),
                                    emojiApkBean.getEmojiWidth(), emojiApkBean.getEmojiHeight(),
                                    emojiApkBean.getItemWidth(), emojiApkBean.getItemHeight(),
                                    emojiApkBean.getPageHeight(), emojiApkBean.getBgColor(), categoryBean.isBuy()));
                            index++;
                        }
                        pageBean2.setPageNum(index - pageBean2.getIndex());
                    }
                } else if (resource instanceof UninstalledStickerResource) {
                    UninstalledStickerResource emojiApkBean = (UninstalledStickerResource) resource;
                    if (emojiApkBean.isExist()) {//存在
                        int emojiNum = emojiApkBean.getEmojiNames().length;
                        int pageNum = emojiNum / emojiApkBean.getEmojiPageNum();
                        if (emojiNum % emojiApkBean.getEmojiPageNum() != 0) {
                            pageNum++;
                        }
                        PagePositionBean pageBean2 = new PagePositionBean();
                        pageBean2.setIndex(index);
                        indexMap.put(emojiApkBean.getPkgName(), pageBean2);
                        for (int k = 0; k < pageNum; k++) {
                            result.add(new EmojiPageBean(EmojiPageBean.TYPE_UNINSTALL_APK, k, emojiApkBean.getPkgName(), emojiApkBean.getEmojiColNum(), emojiApkBean.getEmojiPageNum(),
                                    emojiApkBean.getVerticalSpacing(), emojiApkBean.getHorizontalSpacing(),
                                    emojiApkBean.getEmojiWidth(), emojiApkBean.getEmojiHeight(),
                                    emojiApkBean.getItemWidth(), emojiApkBean.getItemHeight(),
                                    emojiApkBean.getPageHeight(), emojiApkBean.getBgColor(), categoryBean.isBuy()));
                            index++;
                        }
                        pageBean2.setPageNum(index - pageBean2.getIndex());
                    }
                }
            }
        }
        /*//
        ProductDriveStrategy.ProductDriveStrategyConfig config = getEmojiStrategy();
        if (config != null) {
            if (config.isSwitch()) {
                if (!ShareImageTools.getAppIsInstalled(ComponentContext.getContext(), config.getPackageName())) {
                    EmojiPageBean bean = new EmojiPageBean(EmojiPageBean.TYPE_GUIDE_DOWNLOAD, 0, StickerConstant.APK_EMOJI_PKG_NAME);
                    bean.setDownUrl(TextUtils.isEmpty(config.getGpLink()) ?
                            "https://play.google.com/store" : config.getGpLink());
                    result.add(bean);
                    index++;
                }
            }
        }*/
        return result;
    }

    /**
     * 传入第几页
     *
     * @param pageBean
     * @return
     */
    public synchronized ArrayList<EmojiBean> getEmojiData(EmojiPageBean pageBean) {
        ArrayList<EmojiBean> emojiBeans = pageBean.getEmojiBean();
        if (!pageBean.isNeedRefresh() && emojiBeans != null && emojiBeans.size() != 0) {
            return emojiBeans;
        } else {
            ArrayList<EmojiBean> result = new ArrayList<EmojiBean>();
            if (pageBean.isType(EmojiPageBean.TYPE_RESOURCES)) {
                String pkgName = pageBean.getPkgName();
                if (!TextUtils.isEmpty(pkgName)) {
                    StickerApkResource stickerApkResource = mApkBean.get(pkgName);
                    if (stickerApkResource != null) {
                        InsideEmojiResource emojiApkBean = (InsideEmojiResource) stickerApkResource;
                        String[] emojiNames = emojiApkBean.getEmojiNames();
                        int[] emojiIds = emojiApkBean.getEmojiIds();
                        if (emojiNames != null) {
                            int index = pageBean.getEmojiPageIndex();
                            int startPosition = index * pageBean.getPageEmojiNum();
                            int count = pageBean.getPageEmojiNum() + startPosition;
                            int length = emojiNames.length;
                            for (int i = startPosition; i < length && i < count; i++) {
                                EmojiBean emojiBean = new EmojiBean(pkgName, emojiIds[i], emojiNames[i], emojiApkBean.getEditEmojiWidth(), emojiApkBean.getEditEmojiHeight(), emojiApkBean.getName());
                                result.add(emojiBean);
                            }
                        }
                    }
                }
            } else if (pageBean.isType(EmojiPageBean.TYPE_INSTALL_EMOJI_APK)) {
                String pkgName = pageBean.getPkgName();
                if (!TextUtils.isEmpty(pkgName)) {
                    StickerApkResource emojiApkResource = mApkBean.get(pkgName);
                    if (emojiApkResource != null) {
                        Resources resources = emojiApkResource.getRes();
                        String[] emojiNames = emojiApkResource.getEmojiNames();
                        if (emojiNames != null) {
                            int index = pageBean.getEmojiPageIndex();
                            int startPosition = index * pageBean.getPageEmojiNum();
                            int count = pageBean.getPageEmojiNum() + startPosition;
                            int length = emojiNames.length;
                            for (int i = startPosition; i < length && i < count; i++) {
                                EmojiBean emojiBean = new EmojiBean(resources,
                                        emojiNames[i],
                                        pkgName,
                                        EmojiBean.TYPE_INSTALL_EMOJI_APK,
                                        emojiApkResource.getEditEmojiWidth(),
                                        emojiApkResource.getEditEmojiHeight(),
                                        emojiApkResource.isDownloadOnGP(),
                                        emojiApkResource.getName());
                                result.add(emojiBean);
                            }
                        }
                    }
                }
            } else if (pageBean.isType(EmojiPageBean.TYPE_ONLINE)) {
                String pkgName = pageBean.getPkgName();
                if (!TextUtils.isEmpty(pkgName)) {
                    StickerApkResource stickerApkResource = mApkBean.get(pkgName);
                    if (stickerApkResource != null) {
                        OnlineStickerResource onlineResource = (OnlineStickerResource) stickerApkResource;
                        String[] iconUrls = onlineResource.getIconUrls();
                        if (iconUrls != null) {
                            int index = pageBean.getEmojiPageIndex();
                            int startPosition = index * pageBean.getPageEmojiNum();
                            int count = pageBean.getPageEmojiNum() + startPosition;
                            int length = iconUrls.length;
                            for (int i = startPosition; i < length && i < count; i++) {
                                EmojiBean emojiBean = new EmojiBean(pkgName, EmojiBean.TYPE_ONLINE, iconUrls[i], onlineResource.getEditEmojiWidth(), onlineResource.getEditEmojiHeight());
                                result.add(emojiBean);
                            }
                        }
                    }
                }
            } else if (pageBean.isType(EmojiPageBean.TYPE_INSTALL_APK)) {
                String pkgName = pageBean.getPkgName();
                if (!TextUtils.isEmpty(pkgName)) {
                    StickerApkResource stickerApkResource = mApkBean.get(pkgName);
                    if (stickerApkResource != null) {
                        InstalledStickerResource emojiApkBean = (InstalledStickerResource) stickerApkResource;
                        Resources resources = emojiApkBean.getRes();
                        String[] emojiNames = emojiApkBean.getEmojiNames();
                        if (emojiNames != null) {
                            int index = pageBean.getEmojiPageIndex();
                            int startPosition = index * pageBean.getPageEmojiNum();
                            int count = pageBean.getPageEmojiNum() + startPosition;
                            int length = emojiNames.length;
                            for (int i = startPosition; i < length && i < count; i++) {
                                EmojiBean emojiBean = new EmojiBean(resources, emojiNames[i], pkgName, EmojiBean.TYPE_INSTALL_APK_PACKAGE, emojiApkBean.getEditEmojiWidth(), emojiApkBean.getEditEmojiHeight(),emojiApkBean.isDownloadOnGP(), emojiApkBean.getName());
                                result.add(emojiBean);
                            }
                        }
                    }
                }
            } else if (pageBean.isType(EmojiPageBean.TYPE_UNINSTALL_APK)) {
                String pkgName = pageBean.getPkgName();
                if (!TextUtils.isEmpty(pkgName)) {
                    StickerApkResource stickerApkResource = mApkBean.get(pkgName);
                    if (stickerApkResource != null) {
                        UninstalledStickerResource emojiApkBean = (UninstalledStickerResource) stickerApkResource;
                        Resources resources = emojiApkBean.getRes();
                        String[] emojiNames = emojiApkBean.getEmojiNames();
                        if (emojiNames != null) {
                            int index = pageBean.getEmojiPageIndex();
                            int startPosition = index * pageBean.getPageEmojiNum();
                            int count = pageBean.getPageEmojiNum() + startPosition;
                            int length = emojiNames.length;
                            for (int i = startPosition; i < length && i < count; i++) {
                                EmojiBean emojiBean = new EmojiBean(resources, emojiNames[i], pkgName, EmojiBean.TYPE_UNINSTALL_APK_PACKAGE, emojiApkBean.getEditEmojiWidth(), emojiApkBean.getEditEmojiHeight(), emojiApkBean.isDownloadOnGP(), emojiApkBean.getName());
                                result.add(emojiBean);
                            }
                        }
                    }
                }
            } else if (pageBean.isType(EmojiPageBean.TYPE_RECENT)) {
                String emoji = getLastEmoji();
                String[] emojiNames = emoji.split(StickerConstant.SP);
                if (emojiNames != null) {
                    int length = emojiNames.length;
                    for (int i = 0; i < length; i++) {
                        result.add(getEmojiBeanByName(emojiNames[i]));
                    }
                }
            } else if (pageBean.isType(EmojiPageBean.TYPE_AR_STICKER)) {
                String pkgName = pageBean.getPkgName();
                if (!TextUtils.isEmpty(pkgName)) {
                    StickerApkResource stickerApkResource = mApkBean.get(pkgName);
                    if (stickerApkResource != null) {
                        ARStickerResource arStickerResource = ((InsideEmojiResource) stickerApkResource).getARStickerResource();
                        String[] emojiNames = arStickerResource.getEmojiNames();
                        int[] emojiIds = arStickerResource.getEmojiIds();
                        if (emojiNames != null) {
                            int index = pageBean.getEmojiPageIndex();
                            int startPosition = index * pageBean.getPageEmojiNum();
                            int count = pageBean.getPageEmojiNum() + startPosition;
                            int length = emojiNames.length;
                            for (int i = startPosition; i < length && i < count; i++) {
                                EmojiBean emojiBean = new EmojiBean(pkgName, emojiIds[i], emojiNames[i], arStickerResource.getEditEmojiWidth(), arStickerResource.getEditEmojiHeight(), arStickerResource.getName());
                                if (i == 0) {
                                    emojiBean.setARType(EmojiBean.TYPE_AR_TIME_24);
                                    emojiBean.setContainerBean(new TimeStickerBean(TimeStickerBean.TYPE_HOUR_SYSTEM_24));
                                } else if (i == 1) {
                                    emojiBean.setARType(EmojiBean.TYPE_AR_TIME_12);
                                    emojiBean.setContainerBean(new TimeStickerBean(TimeStickerBean.TYPE_HOUR_SYSTEM_12));
                                } else if (i == 2) {
                                    emojiBean.setARType(EmojiBean.TYPE_AR_TIME_ELECT);
                                    emojiBean.setContainerBean(new TimeStickerBean(TimeStickerBean.TYPE_ELECTRON));
                                } else if (i == 3) {
                                    emojiBean.setARType(EmojiBean.TYPE_AR_DATE_WEEK);
                                    emojiBean.setContainerBean(new DateStickerBean(DateStickerBean.TYPE_WEEK));
                                } else if (i == 4) {
                                    emojiBean.setARType(EmojiBean.TYPE_AR_DATE_MONTH);
                                    emojiBean.setContainerBean(new DateStickerBean(DateStickerBean.TYPE_DATE));
                                }
                                result.add(emojiBean);
                            }
                        }
                    }
                }
            }
            pageBean.setEmojiBean(result);
            pageBean.setNeedRefresh(false);
            return result;
        }
    }

    private static final int BTN_SIZE = DeviceUtils.dip2px(ComponentContext.getContext(), 38);
    private static final int EMOJI_BTN_SIZE = DeviceUtils.dip2px(ComponentContext.getContext(), 28);

    private String getIconPath(String pkgName) {
        return com.common.base.utils.FileUtil.getExternalCacheDir(ComponentContext.getContext(), "tmp")
                + File.separator
                + pkgName
                + ".png";
    }

    private void saveIconToFile(Bitmap bitmap, String path) {
        if (bitmap == null) {
            return;
        }
        try {
            BitmapUtils.saveBitmap2(bitmap, path, 100);
        } catch (Exception e) {

        }
    }

    /**
     * 获取底部button栏的icon  注意：这里是同步的
     *
     */
    public synchronized void getButtonIcon(final StickerCategoryBean categoryBean, final EmojiCheckableItem view) {
        try {
            if (categoryBean.getIconType() == StickerCategoryBean.getIconTypeResource()) {
                StickerApkResource apkResource = mApkBean.get(categoryBean.getPkgName());
                if (apkResource instanceof InsideEmojiResource) {
                    GlideApp.with(view)
                            .load(apkResource.getStickerIconId())
                            .override(EMOJI_BTN_SIZE)
                            .into(view.getImageView());
//                    view.setImageResource(apkResource.getStickerIconId());
                } else {
                    Bitmap stickerBtnThumbnail = mIconManager.getStickerBtnThumbnail(categoryBean.getPkgName(), new EmojiIconManager.OnBitmapLoadListener() {
                        @Override
                        public void onBitmapLoad(String pkgName, Bitmap bitmap) {
                            if (view != null && TextUtils.equals((String) view.getTag(), pkgName)
                                    && TextUtils.equals(categoryBean.getPkgName(), pkgName)
                                    && !bitmap.isRecycled()) {
                                String filePath = getIconPath(pkgName);
                                if (!new File(filePath).exists()) {
                                    saveIconToFile(bitmap, filePath);
                                }
                                GlideApp.with(view)
                                        .load(filePath)
                                        .override(BTN_SIZE)
                                        .into(view.getImageView());
//                                GlideApp.with(view)
//                                        .load(bitmap)
//                                        .override(BTN_SIZE)
//                                        .into(view.getImageView());
                            }
                        }

                        @Override
                        public String getPkgName() {
                            return categoryBean.getPkgName();
                        }
                    });
                    if (stickerBtnThumbnail != null && !stickerBtnThumbnail.isRecycled()) {
                        String filePath = getIconPath(categoryBean.getPkgName());
                        if (!new File(filePath).exists()) {
                            saveIconToFile(stickerBtnThumbnail, filePath);
                        }
                        GlideApp.with(view)
                                .load(filePath)
                                .override(BTN_SIZE)
                                .into(view.getImageView());
//                        GlideApp.with(view)
//                                .load(stickerBtnThumbnail)
//                                .override(BTN_SIZE)
//                                .into(view.getImageView());
                    }
//                    view.setImageDrawable(apkResource.getRes().getDrawable(apkResource.getStickerIconId()));
                }
            } else {
                GlideApp.with(view)
                        .load(categoryBean.getUrl())
                        .placeholder(R.drawable.ic_sticker_default)
                        .override(BTN_SIZE)
                        .error(R.drawable.ic_default_image)
                        .into(view.getImageView());
            }
        } catch (Throwable e) {
            view.getImageView().setImageResource(R.drawable.ic_emoji);
        }
    }

    /**
     * 释放内存
     */
    public synchronized void recycle() {
        mIconManager.onDestory();
        isRecycled = true;
        mApkBean.clear();
        mButtonPackages.clear();
    }

    public synchronized void recycleNotBitmap() {
        mIconManager.clearBitmapCache();
        isRecycled = true;
        mApkBean.clear();
        mButtonPackages.clear();
    }

    /**
     * 获取默认的几个Emoji
     *
     * @return
     */
    public synchronized String getDefaultEmoji() {
        StringBuffer bf = new StringBuffer();
        //内置的
        InsideEmojiResource insideEmojiResource = (InsideEmojiResource) mApkBean.get(InsideStickerTool.STICKER_PKG_NAME_EMOJI);
        String EMOJI_NAME[] = insideEmojiResource.getEmojiNames();
        bf.append(EMOJI_NAME[0]).append(StickerConstant.SP);
        bf.append(EMOJI_NAME[1]).append(StickerConstant.SP);
        bf.append(EMOJI_NAME[3]).append(StickerConstant.SP);
        bf.append(EMOJI_NAME[11]).append(StickerConstant.SP);
        bf.append(EMOJI_NAME[16]);
        return bf.toString();
    }

    /**
     * 获取上一次的Emoji的列表  保证获取EmojiBean的时候一定不会为空
     *
     * @return
     */
    public synchronized String getLastEmoji() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ComponentContext.getContext());
        String defalutEmoji = getDefaultEmoji();
        String emoji = preferences.getString(StickerConstant.PREF_KEY_DEFAULT_EMOJI, defalutEmoji);
        if (emoji.equals(defalutEmoji)) {
            return defalutEmoji;
        } else {

            //内置的
            InsideEmojiResource insideEmojiResource = (InsideEmojiResource) mApkBean.get(ComponentContext.getContext().getPackageName());
            String EMOJI_NAME[] = insideEmojiResource.getEmojiNames();

            String names[] = emoji.split(StickerConstant.SP);
            StringBuffer stringBuffer = new StringBuffer();
            int nameLen = names.length;
            int len = EMOJI_NAME.length;
            boolean isNeedResave = false;
            for (int j = 0; j < nameLen; j++) {
                boolean needDefault = false;
                for (int i = 0; i < len; i++) {
                    if (names[j].equals(EMOJI_NAME[i])) {
                        stringBuffer.append(names[j]).append(StickerConstant.SP);
                        needDefault = false;
                        break;
                    } else {
                        needDefault = true;
                    }
                }
                if (needDefault) {
                    isNeedResave = true;
                }
            }
            if (isNeedResave) {//需要将APK中的去掉
                String result = stringBuffer.toString();
                result = result.substring(0, result.length() - 1);
                saveLastEmoji(result);
                return result;
            }

        }
        return emoji;
    }

    /**
     * 保存上次的Emoji的列表
     *
     * @param data
     */
    private synchronized void saveLastEmoji(ArrayList<EmojiBean> data) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ComponentContext.getContext());
        StringBuffer bf = new StringBuffer();
        int len = data.size();
        for (int i = 0; i < len; i++) {
            if (i != len - 1) {
                bf.append(data.get(i).getName()).append(StickerConstant.SP);
            } else {
                bf.append(data.get(i).getName());
            }
        }
        preferences.edit().putString(StickerConstant.PREF_KEY_DEFAULT_EMOJI, bf.toString()).commit();
    }

    /**
     * 保存上次的Emoji的列表
     *
     * @param emojiStr
     */
    private synchronized void saveLastEmoji(String emojiStr) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ComponentContext.getContext());
        preferences.edit().putString(StickerConstant.PREF_KEY_DEFAULT_EMOJI, emojiStr).commit();
    }

    /**
     * 根据Name获取Emojibean
     *
     * @param name
     * @return
     */
    public synchronized EmojiBean getEmojiBeanByName(String name) {
        //内置的
        InsideEmojiResource insideEmojiResource = (InsideEmojiResource) mApkBean.get(InsideStickerTool.STICKER_PKG_NAME_EMOJI);
        String EMOJI_NAME[] = insideEmojiResource.getEmojiNames();
        int EMOJI_ID[] = insideEmojiResource.getEmojiIds();
        int len = EMOJI_NAME.length;
        for (int i = 0; i < len; i++) {
            if (name.equals(EMOJI_NAME[i])) {
                EmojiBean bean = new EmojiBean(InsideStickerTool.STICKER_PKG_NAME_EMOJI, EMOJI_ID[i], EMOJI_NAME[i], insideEmojiResource.getEditEmojiWidth(), insideEmojiResource.getEditEmojiHeight(), insideEmojiResource.getName());
                return bean;
            }
        }

        /*//安装的Emoji APK
        InstalledEmojiResource installEmojiResource = (InstalledEmojiResource) mApkBean.get(StickerConstant.APK_EMOJI_PKG_NAME);
        if (installEmojiResource.isExist()) {
            String mApkEmojiNames[] = installEmojiResource.getEmojiNames();
            if (mApkEmojiNames != null && mApkEmojiNames.length != 0) {
                len = mApkEmojiNames.length;
                for (int i = 0; i < len; i++) {
                    if (name.equals(mApkEmojiNames[i])) {
                        EmojiBean bean = new EmojiBean(installEmojiResource.getRes(), mApkEmojiNames[i], installEmojiResource.getPkgName(), EmojiBean.TYPE_INSTALL_APK_PACKAGE
                                , installEmojiResource.getEditEmojiWidth(), installEmojiResource.getEditEmojiHeight());
                        return bean;
                    }
                }
            }
        }*/
        return null;
    }

    /**
     * 返回值用于标识有无变化
     *
     * @param data
     * @param bean
     * @return
     */
    public synchronized boolean sortEmojiBean(ArrayList<EmojiBean> data, EmojiBean bean) {
        int len = data.size();
        for (int i = 0; i < len; i++) {
            if (data.get(i).getName().equals(bean.getName())) {
                if (i == 0) {//已经在开头了 没变
                    return false;
                } else {
                    data.remove(i);
                    data.add(0, bean);
                    saveLastEmoji(data);
                    return true;
                }
            }
        }
        data.add(0, bean);
        if (data.size() > StickerConstant.DEFAULT_PAGE_EMOJI_NUM) {
            data.remove(data.size() - 1);
        }
        saveLastEmoji(data);
        return true;
    }

    public HashMap<String, StickerApkResource> getApkBean() {
        return mApkBean;
    }

    /**
     * 获取button的所有包名  内置资源的包名和安装的Emoji是同一个  因为他们是同一个Button
     *
     * @return
     */
    public synchronized ArrayList<StickerCategoryBean> getButtonPackages() {
        return new ArrayList<>(mButtonPackages);
    }

    /**
     * 获取bitmap
     *
     * @param bean
     * @return
     */
    public synchronized Bitmap getBitmap(EmojiBean bean) {
        if (bean == null) return null;
        if (bean.isType(EmojiBean.TYPE_RESOURCE)) {
            Resources res = ComponentContext.getContext().getResources();
            return mIconManager.getBitmap(bean, res);
        } else {
            String pkgName = bean.getPackageName();
            StickerApkResource resource = mApkBean.get(pkgName);
            if (resource != null) {
                return mIconManager.getBitmap(bean, resource.getRes());
            } else {
                return null;
            }
        }
    }

    /**
     * 异步加载Emoji和Sticker
     *
     * @param view
     * @param data
     */
    public synchronized void loadEmojiThumbnail(EmojiItem view, EmojiBean data) {
        mIconManager.loadEmojiThumbnail(view, data);
    }

    //清除缓存
    public synchronized void clearBitmapCache() {
        mIconManager.clearBitmapCache();
    }
}
